package animix.blue.server.user.controller;

import animix.blue.server.common.bean.pojo.LogOperationAnno;
import animix.blue.server.common.bean.pojo.Result;
import animix.blue.server.user.service.UserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Api(description = "用户角色关系管理API")
public class UserRoleController {

    @Autowired
    private UserRoleService userRoleService;

    @ApiOperation(value = "获取用户角色", notes = "根据用户id获取用户角色")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Int")
    @GetMapping("/user/{userId}/role")
    public Result getByUserId(@PathVariable Integer userId) {
        return userRoleService.getRoleIdsByUserId(userId);
    }

    @LogOperationAnno(action="设置", object="用户角色")
    @ApiOperation(value = "设置用户角色", notes = "根据用户id设置用户角色")
    @ApiImplicitParam(name = "userId", value = "用户id", required = true, dataType = "Int")
    @PutMapping("/user/{userId}/role")
    public Result setByUserId(@PathVariable Integer userId, @RequestBody Map<String, Object> para) {
        Integer[] roleIds = getRoleIdsFromMap(para);
        return userRoleService.setByUserId(userId, roleIds);
    }

    private Integer[] getRoleIdsFromMap(Map<String, Object> para) {
        List idList = (List<Integer>) para.get("roleIds");
        if (idList != null && idList.size() > 0) {
            Integer[] ids = new Integer[idList.size()];
            for (int i = 0; i < idList.size(); i++) {
                ids[i] = (Integer) idList.get(i);
            }
            return ids;
        } else {
            return null;
        }
    }
}
